import { authorityHttp } from '/@/utils/http/axios';
import { ResourceParams } from '/@/api/system-mgmt/app-resource-mgmt/model/resourceModel';
enum Api {
  GET_RESOURCE_LIST = '/appResource/listResource',
  GET_SUB_RESOURCE_LIST = '/appResource/childrenList',
  CREATE_RESOURCE = '/appResource/createResource',
  UPDATE_RESOURCE = '/appResource/updateResource',
  DELETE_RESOURCE = '/appResource/deleteResource',
}
export const getResourceList = async (params: { appId: string }) => {
  const res = await authorityHttp.get<any[]>({ url: Api.GET_RESOURCE_LIST, params });
  res.forEach((item) => {
    item.title = item.resourceName;
  });
  return res;
};

const changeKey = (tree: any) => {
  tree.key = tree.id;
  tree.title = tree.resourceName;
  if (tree.children !== undefined) {
    tree.children?.forEach((item) => {
      changeKey(item);
    });
  }
};

export const getSubResourceList = async (params: { id: string }) => {
  const res = await authorityHttp.get<any[]>({ url: Api.GET_SUB_RESOURCE_LIST, params });
  res.forEach((item) => {
    changeKey(item);
  });
  return res;
};

export const createResource = (params: ResourceParams) => {
  params.title = params.tempTitle;
  return authorityHttp.post<string>({ url: Api.CREATE_RESOURCE, params });
};

export const updateResource = (params: ResourceParams) => {
  params.title = params.tempTitle;
  return authorityHttp.put<string>({ url: Api.UPDATE_RESOURCE, params });
};

export const deleteResource = (params: { id: string }) => {
  return authorityHttp.delete<string>({ url: Api.DELETE_RESOURCE + '?id=' + params.id });
};
